package com.ytkj.digitalConstruction.controller.assets;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.Page;
import com.ytkj.digitalConstruction.ReturnCode;
import com.ytkj.digitalConstruction.entity.assets.Vehicle;
import com.ytkj.digitalConstruction.httpbean.PageParam;
import com.ytkj.digitalConstruction.httpbean.PageResult;
import com.ytkj.digitalConstruction.httpbean.assets.resbean.ResVehicle;
import com.ytkj.digitalConstruction.service.assets.VehicleService;
import com.ytkj.digitalConstruction.util.WebTokenUtil;

/**
 * 控制层 车辆管理操作的入口
 * 
 * @author
 * @date 2017年12月3日 下午7:04:25
 * @return
 */
@RestController
@RequestMapping("vehicle")
public class VehicleController {

	private Logger log = LoggerFactory.getLogger(getClass());

	/**
	 * 车辆管理Service
	 */
	@Autowired
	private VehicleService vehicleService;

	/**
	 * 增加车辆
	 * 
	 * @param vehicle
	 * @param bindingResult
	 * @return ReturnCode
	 */
	@PostMapping("insertVechicle")
	public ReturnCode insert(@RequestBody @Valid Vehicle vehicle, BindingResult bindingResult) {
		// 判断参数是否合法
		String msg = null;
		if (bindingResult.hasErrors()) {
			msg = bindingResult.getFieldError().getDefaultMessage();
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		// 查询该车牌号是否已存在
		String plateNumber = vehicle.getPlateNumber();
		if (vehicleService.plateNameExists(plateNumber, null)) {
			msg = String.format("车牌号[%s]已存在", plateNumber);
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		// 插入车辆
		if (!vehicleService.insert(vehicle)) {
			msg = String.format("插入车辆[%s]失败", vehicle.getVehicleName());
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		return new ReturnCode.Builder().Success(true).Msg("添加成功").Object(vehicle).build();
	}

	/**
	 * 查找车辆
	 * 
	 * @param request
	 * @param pageParam
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("selectVechicle")
	public ReturnCode select(HttpServletRequest request, @RequestBody @Valid PageParam pageParam,
			BindingResult bindingResult) {
		// 判断参数是否合法
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		//
		int userId = WebTokenUtil.getUserId(request);
		Page<ResVehicle> pageResults = vehicleService.selectAllPageable(userId, pageParam);
		PageResult<ResVehicle> pageResult = new PageResult<ResVehicle>();
		// 查询所有未删除车辆
		log.info("查询所有车辆信息");
		pageResult.setItemTotal(pageResults.getTotal());
		log.info("查询所有车辆信息成功");
		log.info("查询分页车辆信息");
		pageResult.setItems(pageResults.getResult());
		log.info("查询分页车辆信息成功");
		ReturnCode returnCode = new ReturnCode.Builder().Success(true).Msg("查询成功!").Object(pageResult).build();
		return returnCode;
	}

	/**
	 * 删除车辆接口
	 * 
	 * @param id
	 *            删除车辆id
	 * @return ReturnCode
	 */
	@GetMapping("deleteVechicle/{id}")
	public ReturnCode delete(@PathVariable int id) {
		// 判断传入的ID是否为空
		if (id < 1) {
			log.error("传入的车辆id为空或小于1");
			return new ReturnCode.Builder().Success(false).Msg("id不能为负数").build();
		}
		// 删除车辆
		Integer result = vehicleService.delete(id);
		if (result == null || result == 0) {
			log.error("未找到id为" + id + "的车辆，删除失败");
			return new ReturnCode.Builder().Success(false).Msg("删除失败!").build();
		}
		log.info("删除车辆成功");
		return new ReturnCode.Builder().Success(true).Msg("删除成功!").build();
	}

	/**
	 * 修改车辆接口
	 * 
	 * @param vehicle
	 * @param bindingResult
	 * @return ReturnCode
	 */
	@PostMapping("updateVechicle")
	public ReturnCode update(@RequestBody @Valid Vehicle vehicle, BindingResult bindingResult) {
		// 判断参数是否合法
		String msg = null;
		if (bindingResult.hasErrors()) {
			msg = bindingResult.getFieldError().getDefaultMessage();
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		// 判断车辆ID是否为空
		String plateNumber = vehicle.getPlateNumber();
		if (!vehicleService.vehicleExists(vehicle)) {
			msg = String.format("车辆[%s]不存在.", plateNumber);
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		// 判断车牌是否存在
		Integer vehicleId = vehicle.getVehicleId();
		if (vehicleService.plateNameExists(plateNumber, vehicleId)) {
			msg = String.format("车牌号[%s]已存在，修改失败", plateNumber);
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		// 绑定设备
		Integer bindDevice = vehicle.getBindDevice();
		// 当前的车辆状况
		Vehicle vehicle2 = vehicleService.select(vehicleId);
		Integer deviceId = vehicle2.getBindDevice();
		// 绑定设备id为空
		if (bindDevice == null) {
			// 1.之前没有（不用处理）；2.之前有
			if (deviceId != null && deviceId > 0 && !vehicleService.unbindDevice(deviceId)) {
				msg = String.format("设备[id:%s]解绑车辆[id:%s]失败", deviceId, vehicleId);
				log.error(msg);
				return new ReturnCode.Builder().Success(false).Msg(msg).build();
			}
			vehicle.setBindDevice(0);
		} else { // 绑定设备id不为空
			// 1.之前没有，检查并绑定
			// 2.之前有，但是不是用一个，检查并绑定；
			if ((deviceId == null || deviceId == 0) || (deviceId != null && deviceId > 0 && deviceId != bindDevice)) {
				if (!vehicleService.checkDeviceAndBind(bindDevice, vehicleId)) {
					msg = String.format("设备[id:%s]绑定车辆[id:%s]失败", deviceId, vehicleId);
					log.error(msg);
					return new ReturnCode.Builder().Success(false).Msg(msg).build();
				}
			}
		}
		// 修改车辆
		Integer result = vehicleService.update(vehicle);
		if (result == null || result == 0) {
			msg = String.format("修改车牌%s的车辆失败", plateNumber);
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		log.info("修改车牌为" + vehicle.getPlateNumber() + "的车辆成功");
		return new ReturnCode.Builder().Success(true).Msg("修改成功").build();
	}

}
